﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Windows.Forms;

namespace DbTask
{
    public class Utils
    {
        public static string AppFolder()
        {
            return Path.GetDirectoryName(Application.ExecutablePath);
        }

        public static string DownloadFolder()
        {
            string path = AppFolder() + @"\Downloads";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            return path;
        }


        public static void AddLog(string text)
        {
            string filename = AppFolder() + @"\Logs\" + DateTime.Today.ToString("dd.MM.yyyy") + ".log";
            if (filename != "")
            {
                if (!Directory.Exists(Path.GetDirectoryName(filename)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(filename));
                }
                if (!File.Exists(filename))
                {
                    File.Create(filename).Close();
                }
                StreamWriter sw = File.AppendText(filename);
                sw.WriteLine(DateTime.Now + " " + text);
                sw.Close();
            }
        }

        public static void DataTableToCsv(DataTable dt, string fileName)
        {
            StringBuilder sb = new StringBuilder();

            IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                              Select(column => column.ColumnName);
            sb.AppendLine(string.Join(",", columnNames));

            foreach (DataRow row in dt.Rows)
            {
                IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
                sb.AppendLine(string.Join(",", fields));
            }

            File.WriteAllText(fileName, sb.ToString());
        }
    }
}
